<header id="header" class="d-flex flex-column align-items-end hidden-xs" role="banner">
    <div class="header-inner d-flex flex-column align-items-end">
        <div class="app-header d-flex flex-column">
            <div class="d-flex flex-column">
                <h1 class="app-logo py-3" role="heading">
                    <a href="/"><img class="rounded-circle" src="/img/logo.png" alt=""></a>
                </h1>
                <nav class="app-nav d-flex flex-column" role="navigation">
                    <a href="/" class="app-link" data-active="home" title="主页">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-home"></i>
                            <div class="nav-link px-3 fs-18">主页</div>
                            <div class="unread-dot"></div>
                        </div>
                    </a>
                    <a class="app-link" href="/explore" data-active="explore" title="探索">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-search"></i>
                            <div class="nav-link px-3 fs-18">探索</div>
                        </div>
                    </a>
                    <!-- <a class="app-link" href="/lists" data-active="lists" title="列表">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-lists"></i>
                            <div class="nav-link px-3 fs-18">列表</div>
                        </div>
                    </a> -->
                    <a href="/group" class="app-link" data-active="group" title="社群">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-pal"></i>
                            <div class="nav-link px-3 fs-18">社群</div>
                        </div>
                    </a>
                    <a class="app-link" href="/message" data-active="message" title="通知">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-notifications"></i>
                            <div class="nav-link px-3 fs-18">通知</div>
                            <div class="unread-message">2</div>
                        </div>
                    </a>
                    <!-- <a class="app-link" href="/post" data-active="post" title="探索">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-topics"></i>
                            <div class="nav-link px-3 fs-18">动态</div>
                        </div>
                    </a> -->
                    <a href="/reward" class="app-link" data-active="reward" title="奖励">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-present"></i>
                            <div class="nav-link px-3 fs-18">奖励</div>
                        </div>
                    </a>
                    <!-- <a href="/medal" class="app-link" data-active="medal" title="勋章">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-medal"></i>
                            <div class="nav-link px-3 fs-18">勋章</div>
                        </div>
                    </a> -->
                <?php if(session('user_id')): ?>
                    <a class="app-link" href="/user/profile/<?= session('user_id') ?>" data-active="user" title="个人资料">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-user"></i>
                            <div class="nav-link px-3 fs-18">个人资料</div>
                        </div>
                    </a>
                    <div class="dropup">
                        <a class="app-link" href="###" data-bs-toggle="dropdown" aria-expanded="false" data-active="more" title="更多">
                            <div class="nav-item d-inline-flex">
                                <i class="iconfont icon-more3"></i>
                                <div class="nav-link px-3 fs-18">更多</div>
                            </div>
                        </a>
                        <ul class="dropdown-menu shadow">
                            <li><a class="dropdown-item" href="/medal"><i class="iconfont icon-medal me-2"></i> 勋章</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/user/logout">退出</a></li>
                        </ul>
                    </div>
                    <button type="button" class="btn btn-primary create-post rounded-pill hidden-md hidden-xs hidden-sm" data-bs-toggle="modal" data-bs-target="#createPost">
                        <i class="iconfont icon-feather hidden-lg hidden-md"></i>
                        <div class="nav-link">发帖</div>
                    </button>
                    <!-- 小屏显示的发帖按钮 -->
                    <a href="javaxript:;" class="twteet-btn hidden-lg" data-bs-toggle="modal" data-bs-target="#createPost" title="发帖">
                        <div class="nav-item d-inline-flex justify-content-center">
                            <i class="iconfont icon-feather"></i>
                        </div>
                    </a>
                <?php else: ?>
                    <a class="app-link" href="/user/login" data-active="user" title="登录">
                        <div class="nav-item d-inline-flex">
                            <i class="iconfont icon-user"></i>
                            <div class="nav-link px-3 fs-18">登录</div>
                        </div>
                    </a>
                <?php endif; ?>
                </nav>
            </div>
        </div>
    </div>
</header>

<!-- Modal -->
<div class="modal fade" id="createPost" tabindex="-1" aria-labelledby="createPostLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-18" id="createPostLabel">发帖</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body composer home-composer d-flex pt-1">
                <img class="avatar" src="/img/avatar.jpg" alt="">
                <div class="flex-fill">
                    <form id="post-form" action="/post/submit" method="POST" enctype="multipart/form-data">
                        <textarea class="form-control border-0 px-0 js-lock-btn js-textarea" name="content" id="content" maxlength="200" spellcheck="false" placeholder="良言一句三冬暖，恶语伤人六月寒" required autofocus></textarea>
                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                        <input type="file" class="d-none" name="files[]" id="files" accept="image/png,image/jpeg,image/gif" multiple>
                        <div class="composer-action d-flex justify-content-between align-items-center mb-2">
                            <?= mini\Template::partial('partials/_post_toolbar') ?>
                            <div>
                                <span class="textarea-count" id="counter">200</span>
                                <?php if (isset($user) && isset($user->golds) <= 0) : ?>
                                    <button type="button" class="btn btn-primary fw-bold" disabled>金币不足</button>
                                <?php else : ?>
                                    <!-- <button type="button" id="submitButton" class="btn btn-primary fw-bold submitButton" disabled>发帖</button> -->
                                    <button type="submit" class="btn btn-primary fw-bold rounded-pill">发帖</button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                    <div id="previewContainer"></div>
                    <!-- <img class="previewImg img-fluid rounded mb-2" id="previewImg"> -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 发帖
document.addEventListener('DOMContentLoaded', function () {
    const MAX_FILES = 4; // 最多允许上传的文件数量
    const file_input = document.getElementById('files');
    const files = file_input.files;

    // 验证发帖内容
    function validateContent() {
        const content = document.getElementById('content').value.trim();
        return content.length > 0;
    }

    // 点击发帖按钮后验证
    const submitButton = document.querySelector('.submitButton');
    if (submitButton) {
        submitButton.addEventListener('click', function () {
        if (files.length > MAX_FILES) {
            toast.info(`一次最多上传 ${MAX_FILES} 张图片！`);
            return;
        }
        if (!validateContent()) {
            toast.info('请输入帖子内容');
            return;
        }
        let data = new FormData(document.getElementById('post-form'));
        fetch('/post/submit', { method: 'POST', body: data })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'success') {
                    // 显示成功消息
                    toast.success(res.message);
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    // 显示错误消息
                    toast.error(res.message);
                }
            })
            .catch(error => {
                toast.error('上传文件失败。');
            });
        });
    }

    /**
     * 预览要上传的图片
     */
    const fileEle = document.getElementById('files');
    const previewContainer = document.getElementById('previewContainer');
    let selectedFiles = []; // 用于存储用户选择的文件

    fileEle.addEventListener('change', function (e) {
        // 清空之前的预览和文件列表
        previewContainer.innerHTML = '';
        selectedFiles = [];

        // 获取所有选中的文件
        const files = e.target.files;

        // 遍历文件并创建预览
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            selectedFiles.push(file); // 将文件添加到自定义列表中

            const url = URL.createObjectURL(file);
            const img = document.createElement('img');
            img.src = url;
            img.style.width = '100px';
            img.style.height = 'auto';
            img.style.margin = '5px';
            img.style.cursor = 'pointer'; // 表示可点击

            // 为图片添加点击事件监听器
            img.addEventListener('click', function () {
                // 从预览容器中移除图片
                previewContainer.removeChild(this);

                // 从自定义文件列表中移除文件
                const index = selectedFiles.indexOf(file);
                if (index !== -1) {
                    selectedFiles.splice(index, 1);
                }

                // 释放URL对象
                URL.revokeObjectURL(this.src);
            });

            // 将img元素添加到预览容器中
            previewContainer.appendChild(img);
        }
    });

    /**
     * 计算剩余字符数
     */
    const contentEle = document.getElementById('content');
    const counterEle = document.getElementById('counter');
    contentEle.addEventListener('input', function (e) {
        const target = e.target;
        const maxLength = 200;
        // 计算当前的字符数
        const currentLength = getStringLength(target.value);
        counterEle.innerHTML = Math.floor(maxLength - currentLength);
    });

    // const sources = document.querySelectorAll('textarea');
    // if (sources.length >= 1) {
    //     const h_editor =new TE(sources[0]);  // 首页编辑器
    // }
    // if (sources.length >= 2) {
    //     const c_editor = new TE(sources[1]);  // 评论框编辑器
    // }
});
</script>